package com.mccken.rapid.core.context;

import org.asynchttpclient.Response;

import com.fasterxml.jackson.databind.node.ObjectNode;
import com.mccken.rapid.common.enums.ResponseCode;
import com.mccken.rapid.common.util.JSONUtil;

import io.netty.handler.codec.http.DefaultHttpHeaders;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpResponseStatus;
import lombok.Data;

/**
 * 网关响应封装类
 * 
 * @program: rapid_gateway
 * @description:
 * @author: mccken
 * @create: 2022-01-29 15:07
 **/
@Data
public class RapidResponse {
	
	// 响应头
	private HttpHeaders responseHeaders = new DefaultHttpHeaders();
	
	// 额外的响应结果
	private final HttpHeaders extraResponseHeaders = new DefaultHttpHeaders();
	
	// 返回响应状态码
	private HttpResponseStatus httpResponseStatus;
	
	// 返回的响应内容
	private String content;
	
	// 响应对象
	private Response futureResponse;
	
	private RapidResponse(){}
	
	// 设置响应头i信息
	public void putHeader(CharSequence key, CharSequence val) {
		responseHeaders.add(key, val);
	}
	
	public static RapidResponse buildRapidResponse(Response futureResponse) {
		RapidResponse rapidResponse = new RapidResponse();
		rapidResponse.setFutureResponse(futureResponse);
		rapidResponse.setHttpResponseStatus(HttpResponseStatus.valueOf(futureResponse.getStatusCode()));
		return rapidResponse;
	}
	
	public static RapidResponse buildRapidResponse(ResponseCode code, Object... args) {
		ObjectNode objectNode = JSONUtil.createObjectNode();
		objectNode.put(JSONUtil.STATUS, code.getStatus().code());
		objectNode.put(JSONUtil.CODE, code.getCode());
		objectNode.put(JSONUtil.MESSAGE, code.getMessage());

		RapidResponse rapidResponse = new RapidResponse();
		rapidResponse.setHttpResponseStatus(code.getStatus());
		rapidResponse.putHeader(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON + ";charset=utf-8");
		rapidResponse.setContent(JSONUtil.toJSONString(objectNode));
		return rapidResponse;
	}
	
	public static RapidResponse buildRapidResponse(Object data) {
		ObjectNode objectNode = JSONUtil.createObjectNode();
		objectNode.put(JSONUtil.STATUS, ResponseCode.SUCCESS.getStatus().code());
		objectNode.put(JSONUtil.CODE, ResponseCode.SUCCESS.getCode());
		objectNode.putPOJO(JSONUtil.DATA, data);

		RapidResponse rapidResponse = new RapidResponse();
		rapidResponse.setHttpResponseStatus(ResponseCode.SUCCESS.getStatus());
		rapidResponse.putHeader(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON + ";charset=utf-8");
		rapidResponse.setContent(JSONUtil.toJSONString(objectNode));
		return rapidResponse;
	}
}
